package com.theexceptions.todo.view;

import com.google.android.maps.OverlayItem;
import com.theexceptions.todo.controller.SearchMapController;
import com.theexceptions.todo.model.Location;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;

/**
 * An overlay of location pins to show where tasks are located.
 * 
 * @author Justian Meyer
 */
public class SelectLocationItemizedOverlay extends LocationItemizedOverlay {

	private Activity activity; 
	
	public SelectLocationItemizedOverlay(Drawable defaultMarker, Activity activity) {
		super(defaultMarker, activity);
		this.activity = activity;
	}

	/**
	 * Handles actions when overlay item is tapped. The user will be shown a
	 * yes/no dialog box asking if they would like to set the tapped location as
	 * their new task's location.
	 * 
	 * @param index Item index
	 * @return boolean
	 */
	@Override
	protected boolean onTap(int index) {
		final OverlayItem item = overlays.get(index);

		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					String[] split = item.getSnippet().split(" ");

					long id = Long.parseLong(split[0]);
					String name = item.getTitle();
					int lat = Integer.parseInt(split[1]);
					int lon = Integer.parseInt(split[2]);

					SearchMapController.setLocation(new Location(id, name, lat, lon));
					
					activity.setResult(1000);
					activity.finish(); // finish map activity
					
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					break;
				}
			}
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setMessage("Set the location as \"" + item.getTitle() + "\"?")
				.setPositiveButton("Yes", dialogClickListener)
				.setNegativeButton("No", dialogClickListener).show();

		return true;
	}

}
